<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace uctoo\job;

use catchAdmin\wechatopen\model\Applet;
use uctoo\util\library\Mpopen;
use think\queue\Job;


class SetSubscribeMessageTpl
{

    public function fire(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            $job->delete();
            return true;
        }
        $applet = $data['applet'];
        $app = invoke(Mpopen::class);
        $app = $app->miniProgram($applet['appid'], $applet['refresh_token']);
        $app->config->add('env', $applet['env']);
        $app->rebind('cache', app('cache'));

        // 设置订阅消息模板
        $res = $app->subscribe_message->getTemplates();
        foreach ($res['data'] as $tpl){
            // 删除所有
            $app->subscribe_message->deleteTemplate($tpl['priTmplId']);
        }
        $tpls = [];
        foreach ($data['subscribe_message_tpl'] as $tpl) {
            $res = $app->subscribe_message->addTemplate($tpl['tid'], $tpl['kid_list'], $tpl['scene_desc']);
            isset($res['priTmplId']) && $tpls[$tpl['key']] = $res['priTmplId'];
        }

        // 保存至云数据库
        $cloud_db = $app->register(new \app\util\src\MiniPrograme\CloudDb\ServiceProvider())->cloud_db;
        /**
         * @var \app\util\src\MiniPrograme\CloudDb\Client $cloud_db
         */
        $query = 'db.collection("config").doc("subscribe_message_tpl").set({data:{value: '.json_encode($tpls).'}})';
        $cloud_db->update($query);

        $job->delete();
    }

    public function failed($data)
    {

    }
}